<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script>
/*
 * 1.文档加载完成后
 		获取所有省份，添加到select中
 	2.给select标签这个元素添加onchange事件
 		事件内容：
 			1.获取当前省id
 			2.使用省id访问servlet得到该省所有市
 			3.把每个市添加到第二个select中
 */
 
 function createXMLHttpRequest() {
	try {
		return new XMLHttpRequest();
	} catch(e) {
		try {
			return new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				return new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				throw e;
			}
		}
	}
}
 
window.onload = function() {
	/*
		发送异步请求，得到所有省份，使用每一个省生成一个option
	*/
	var province = document.getElementById("province");
	
	var xmlHttp = createXMLHttpRequest();
	xmlHttp.open("GET", "<c:url value='/ProvinceServlet' />", true);
	xmlHttp.send(null);
	xmlHttp.onreadystatechange = function() {
		if(xmlHttp.readyState == 4) {
			if(xmlHttp.status == 200) {
				//这里eval函数的作用是执行这个字符串Js语句，如果加上括号，则直接
				//返回括号里面的对象
				var proArray = eval("(" + xmlHttp.responseText + ")");
				for(var i = 0; i < proArray.length; i++) {
					var pro = proArray[i];
					var optionEle = document.createElement("option");
					optionEle.value = pro.proID;
					var textNode = document.createTextNode(pro.proName);
					optionEle.appendChild(textNode);
					
					province.appendChild(optionEle);
				}
			}
		}
	};
	
	province.onchange = function() {
		var cityEle = document.getElementById("city");
		var cityOptionArray = cityEle.getElementsByTagName("option");
		while(cityOptionArray.length > 1) {
			cityEle.removeChild(cityOptionArray[1]);
		}
		
		var xmlHttp = createXMLHttpRequest();
		xmlHttp.open("POST", "<c:url value='/CityServlet' />", true);
		xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlHttp.send("proID=" + this.value);
		xmlHttp.onreadystatechange = function() {
			if(xmlHttp.readyState == 4) {
				if(xmlHttp.status == 200) {
					var cityArray = eval("(" + xmlHttp.responseText + ")");
					for(var i = 0; i < cityArray.length; i++) {
						var city = cityArray[i];
						var optionEle = document.createElement("option");
						//option.value = city.cityName;
						var textNode = document.createTextNode(city.cityName);
						optionEle.appendChild(textNode);
						
						cityEle.appendChild(optionEle);
					}
				}
			}
		};
	};
};
</script>
</head>
<body>
<h1>省市联动实例</h1>
<select id="province">
	<option>==请选择省份==</option>
</select>
&nbsp;&nbsp;&nbsp;
<select id="city">
	<option>==请选择城市==</option>
</select>
</body>
</html>